package data;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import fields.CreditCard;
import fileProcessing.ParsingException;

public class CreditCardNumberEntry extends AbstractDataType<CreditCardNumberEntry>{
	
	private int creditCardNumber;
	private String creditCardType;
	private String fieldType = "Credit Card";
	
	public CreditCardNumberEntry(){};
	
	public CreditCardNumberEntry(RandomAccessFile raf) throws ParsingException{
		try {
			creditCardNumber = raf.readInt();
		} catch (IOException e) {
			throw new ParsingException("Error: "+e.getMessage()+" when reading date from table's data file");
		}
	}
	
	public CreditCardNumberEntry(String ccNum) throws ParsingException{
		if(isValid(ccNum)){
			creditCardNumber = creditCardNumber;
			creditCardType = checkType(ccNum);
		}
		else
			throw new ParsingException("Phone number not valid.");
	}
	
	private String checkType(String ccNum) {
		Pattern visa = Pattern.compile("4[0-9]{12}(?:[0-9]{3})?");
		Pattern masterCard = Pattern.compile("5[1-5][0-9]{14}");
		Pattern discoverCard = Pattern.compile("6(?:011|5[0-9]{2})[0-9]{12}");
		Pattern americanExpress = Pattern.compile("3[47][0-9]{13}");
		Pattern dinersClub = Pattern.compile("3(?:0[0-5]|[68][0-9])[0-9]{11}");
		Pattern jcb = Pattern.compile("(?:2131|1800|35\\d{3})\\d{11}");
		
		if(visa.matcher(ccNum).matches()){
			return "Visa";
		}
		else if(masterCard.matcher(ccNum).matches()){
			return "MasterCard";
		}
		else if(discoverCard.matcher(ccNum).matches()){
			return "Discover";
		}
		else if(americanExpress.matcher(ccNum).matches()){
			return "American Express";
		}
		else if(dinersClub.matcher(ccNum).matches()){
			return "Diners Club";
		}
		else if(jcb.matcher(ccNum).matches()){
			return "JCB";
		}
		else
			return "";
	}

	public boolean isValid(String val){
		Pattern pattern = Pattern.compile("(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|" +
				"6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|" +
				"(?:2131|1800|35\\d{3})\\d{11})");
		Matcher matcher = pattern.matcher(val);
		return matcher.matches();
	}

	@Override
	public int compareTo(CreditCardNumberEntry o) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String getType() {
		return fieldType;
	}

}
